package jjn.round2;

import commons.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * @author Jiang Jining
 * @since 2023-05-28 23:05
 */
public class Offer44_2_LargestValues {
    public List<Integer> largestValues(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root == null) {
            return new ArrayList<>();
        }
        queue.add(root);
        List<Integer> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            int max = Integer.MIN_VALUE;
            int size = queue.size();
            while (size > 0 && !queue.isEmpty()) {
                TreeNode node = queue.poll();
                max = Math.max(node.val, max);
                TreeNode left = node.left;
                if (left != null) {
                    queue.offer(left);
                }
                TreeNode right = node.right;
                if (right != null) {
                    queue.offer(right);
                }
                size--;
            }
            result.add(max);
        }
        return result;
    }
    
}
